package com.lianzhihui.romeex.ui.mianfragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

import com.lianzhihui.romeex.MyApplication;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.MyTeamBean;
import com.lianzhihui.romeex.bean.OrePoolBean;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.mvp.presenter.OrePoolFragmentPresnterImp;
import com.lianzhihui.romeex.mvp.view.OrePoolFragmentView;
import com.lianzhihui.romeex.ui.base.BaseFragment;
import com.lianzhihui.romeex.ui.me.InvitationActivity;
import com.lianzhihui.romeex.ui.orepool.MiningEarningsActivity;
import com.lianzhihui.romeex.ui.orepool.MyTeamActivity;
import com.lianzhihui.romeex.ui.orepool.RankActivity;
import com.lianzhihui.romeex.utils.IntentUtils;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.NoDoubleClickUtils;
import com.lianzhihui.romeex.utils.NumberUtils;
import com.lianzhihui.romeex.utils.PreferenceUtils;
import com.lianzhihui.romeex.utils.StatusBarUtil;
import com.lianzhihui.romeex.widget.MyRoundProcess;
import com.lianzhihui.romeex.widget.dialog.OrePoolChartDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.MessageFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * ProjectName: romeex
 * Package: com.lianzhihui.romeex.ui.ecological
 * ClassName: OrePoolFragment
 * Description: 矿池
 * Author: zhanghong
 * CreateDate: 2020/10/26 15:13
 * UpdateUser: 更新者：
 * UpdateDate: 2020/10/26 15:13
 * UpdateRemark: 更新说明：
 * Version: 1.0
 */
public class OrePoolFragment extends BaseFragment implements OrePoolFragmentView, OnRefreshListener {

    public final boolean isOpenFunction = false;
    @BindView(R.id.status_bar_id)
    View statusBarId;
    @BindView(R.id.earnings_layout)
    View earningsLayout;
    @BindView(R.id.imageView2)
    ImageView imageView2;
    @BindView(R.id.icon_my_level)
    ImageView icon_my_level;
    @BindView(R.id.icon_community_level)
    ImageView icon_community_level;
    @BindView(R.id.iv_price)
    TextView ivPrice;
    @BindView(R.id.fx_count)
    TextView fxCount;
    @BindView(R.id.tv_pd_count)
    TextView tv_pd_count;
    @BindView(R.id.tv_my_level)
    TextView tv_my_level;
    @BindView(R.id.tv_community_level)
    TextView tv_community_level;
    @BindView(R.id.tv_community_level_empty)
    TextView tv_community_level_empty;
    @BindView(R.id.num1)
    TextView num1;
    @BindView(R.id.num2)
    TextView num2;
    @BindView(R.id.num3)
    TextView num3;
    @BindView(R.id.num4)
    TextView num4;
    @BindView(R.id.num5)
    TextView num5;
    @BindView(R.id.num6)
    TextView num6;
    @BindView(R.id.num7)
    TextView num7;
    @BindView(R.id.total_mings)
    TextView totalMings;
    @BindView(R.id.total_waiting)
    TextView totalWaiting;
    @BindView(R.id.total_pledge)
    TextView totalPledge;
    @BindView(R.id.total_destroy)
    TextView totalDestroy;
    @BindView(R.id.total_placement)
    TextView totalPlacement;
    @BindView(R.id.rolling_pool_ret)
    TextView rollingPoolRet;
    @BindView(R.id.tv_my_level_empty)
    TextView tv_my_level_empty;
    @BindView(R.id.tv_direct)
    TextView tv_direct;
    @BindView(R.id.tv_teamValid)
    TextView tv_teamValid;
    @BindView(R.id.myScrollView)
    NestedScrollView myScrollView;
    @BindView(R.id.mySmartRefreshLayout)
    SmartRefreshLayout mySmartRefreshLayout;
    @BindView(R.id.rollingPoolRUSD)
    TextView rollingPoolRUSD;
    @BindView(R.id.destroyPoolRET)
    TextView destroyPoolRET;
    @BindView(R.id.sportsPoolRET)
    TextView sportsPoolRET;
    @BindView(R.id.loanPoolRET)
    TextView loanPoolRET;
    @BindView(R.id.total_mings_pb)
    ProgressBar totalMingsPb;
    @BindView(R.id.total_waiting_pb)
    ProgressBar totalWaitingPb;
    @BindView(R.id.total_pledge_pb)
    ProgressBar totalPledgePb;
    @BindView(R.id.total_destroy_pb)
    ProgressBar totalDestroyPb;
    @BindView(R.id.total_placement_pb)
    ProgressBar totalPlacementPb;
    @BindView(R.id.message1)
    TextView message1;
    @BindView(R.id.message2)
    TextView message2;
    @BindView(R.id.message3)
    TextView message3;
    @BindView(R.id.message4)
    TextView message4;
    @BindView(R.id.my_round_process1)
    MyRoundProcess myRoundProcess1;
    @BindView(R.id.my_round_process2)
    MyRoundProcess myRoundProcess2;
    @BindView(R.id.my_round_process3)
    MyRoundProcess myRoundProcess3;
    @BindView(R.id.my_round_process4)
    MyRoundProcess myRoundProcess4;
    @BindView(R.id.my_round_process5)
    MyRoundProcess myRoundProcess5;
    @BindView(R.id.total_mings_layout)
    RelativeLayout totalMingsLayout;
    @BindView(R.id.total_waiting_layout)
    RelativeLayout totalWaitingLayout;
    @BindView(R.id.total_pledge_layout)
    RelativeLayout totalPledgeLayout;
    @BindView(R.id.total_destroy_layout)
    RelativeLayout totalDestroyLayout;
    @BindView(R.id.total_placement_layout)
    RelativeLayout totalPlacementLayout;
    private OrePoolFragmentPresnterImp myTeamPresnterImp;
    MyTeamBean teamBean;
    private String inviteCode = "";
    private List<OrePoolBean.PledgeAmountTrendBean.SevenPledgeAmountBean> sevenPledgeAmount;
    private List<OrePoolBean.PriceTrendBean.SevenPriceBean> sevenPrice;
    private String pledgeAmount;
    private String waitingPledgeAmount;
    private String totalAward;
    private String yesterdayAward;
    private String retPrice = "0";
    private String retPriceCNY = "0";
    private String wholePledgeAmount;
    // the fragment initialization parameters,e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ore_pool;
    }


    public OrePoolFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    public static OrePoolFragment newInstance() {
        OrePoolFragment fragment = new OrePoolFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, "");
        args.putString(ARG_PARAM2, "");
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarId.getHeight());
        layoutParams.topMargin = StatusBarUtil.getStatusBarHeight(MyApplication.mContext);
        mySmartRefreshLayout.setOnRefreshListener(this);
        statusBarId.setLayoutParams(layoutParams);
        myTeamPresnterImp = new OrePoolFragmentPresnterImp(getActivity(), this);
        mySmartRefreshLayout.autoRefresh();
    }


    @Override
    public void onResume() {
        super.onResume();
        setTitlePrice();
    }

    @OnClick({R.id.earnings_layout, R.id.tv_rank, R.id.iv_inv, R.id.imageView2, R.id.my_team_layout})
    public void onClick(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            switch (view.getId()) {
                case R.id.earnings_layout:
                    //我的挖矿收益
                    if (!isOpenFunction) {
                        String[] strings = new String[]{pledgeAmount, waitingPledgeAmount, totalAward, yesterdayAward};
                        IntentUtils.JumpToHaveStringArray(MiningEarningsActivity.class, AppConstants.INTENT_MINGS, strings);
                    } else {
                        Toast.makeText(getContext(), R.string.text_will_be_open, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.tv_rank:
                    //排行榜
                    if (isOpenFunction) {
                        IntentUtils.JumpTo(RankActivity.class);
                    } else {
                        Toast.makeText(getContext(), R.string.text_will_be_open, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.iv_inv:
                    //邀请
                    if (!inviteCode.isEmpty()) {
                        IntentUtils.JumpToHaveOne(InvitationActivity.class, AppConstants.INTENT_INVITATION_CODE, inviteCode);
                    } else {
                        Toast.makeText(getContext(), R.string.text_will_be_open, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.imageView2:
                    //走势图
                    if (sevenPledgeAmount != null && sevenPrice != null) {
                        OrePoolChartDialog orePoolChartDialog = new OrePoolChartDialog(getActivity());
                        orePoolChartDialog.setData(sevenPledgeAmount, sevenPrice, wholePledgeAmount);
                        orePoolChartDialog.fullWidth();
                        orePoolChartDialog.center();
                        orePoolChartDialog.show();
                    }
                    break;
                case R.id.my_team_layout:
                    //我的团队
                    IntentUtils.JumpToHaveObj(MyTeamActivity.class, AppConstants.TEAM_BEAN, teamBean);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
//        mySmartRefreshLayout.autoRefresh();
    }


    private void setCommunityData(int level) {
        Drawable drawable = getResources().getDrawable(R.drawable.icon_community1);
        switch (level) {
            case 1:
                drawable = getResources().getDrawable(R.drawable.icon_community1);
                break;
            case 2:
                drawable = getResources().getDrawable(R.drawable.icon_community2);
                break;
            case 3:
                drawable = getResources().getDrawable(R.drawable.icon_community3);
                break;
            case 4:
                drawable = getResources().getDrawable(R.drawable.icon_community4);
                break;
            case 5:
                drawable = getResources().getDrawable(R.drawable.icon_community5);
                break;
            default:
                break;
        }
        icon_community_level.setImageDrawable(drawable);
    }

    private void setMyLevelData(int level) {
        Drawable drawable = getResources().getDrawable(R.drawable.icon_grade1);
        switch (level) {
            case 1:
                drawable = getResources().getDrawable(R.drawable.icon_grade1);
                break;
            case 2:
                drawable = getResources().getDrawable(R.drawable.icon_grade2);
                break;
            case 3:
                drawable = getResources().getDrawable(R.drawable.icon_grade3);
                break;
            case 4:
                drawable = getResources().getDrawable(R.drawable.icon_grade4);
                break;
            case 5:
                drawable = getResources().getDrawable(R.drawable.icon_grade5);
                break;
            case 6:
                drawable = getResources().getDrawable(R.drawable.icon_grade6);
                break;
            case 7:
                drawable = getResources().getDrawable(R.drawable.icon_grade7);
                break;
            case 8:
                drawable = getResources().getDrawable(R.drawable.icon_grade8);
                break;
            case 9:
                drawable = getResources().getDrawable(R.drawable.icon_grade9);
                break;
            case 10:
                drawable = getResources().getDrawable(R.drawable.icon_grade10);
                break;
            default:
                break;
        }
        icon_my_level.setImageDrawable(drawable);
    }

    @Override
    public void setFailure() {
        mySmartRefreshLayout.finishRefresh();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        myTeamPresnterImp.requestRollingPoolIndex();
    }


    @Override
    public void responseRollingPoolIndexSuccess(OrePoolBean bean) {
        if (bean != null && isAdded()) {
            //邀请码
            inviteCode = bean.getInviteCode();
            //usdt价格
            retPrice = bean.getRetPrice();
            //cny价格
            retPriceCNY = bean.getRetPriceCNY();
            //全网复兴值数据
            if (bean.getPledgeAmountTrend() != null) {
                sevenPledgeAmount = bean.getPledgeAmountTrend().getSevenPledgeAmount();
            }
            //价格走势数据
            sevenPrice = bean.getPriceTrend().getSevenPrice();
            //全网复兴值
            wholePledgeAmount = bean.getWholeNetworkInfo().getWholePledgeAmount();
            num1.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(wholePledgeAmount))));
            //全网排单量
            num2.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(bean.getWholeNetworkInfo().getWholeWaitingAmount()))));
            //新增目标值
            num3.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(bean.getWholeNetworkInfo().getTodayAddAmount()))));
            //昨日新增值
            num4.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(bean.getWholeNetworkInfo().getYesterdayAddAmount()))));
            //复兴值系数
            num5.setText(bean.getWholeNetworkInfo().getHashrateCoefficient());
            //昨日总挖矿
            num6.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getWholeNetworkInfo().getYesterdayTotalMings())), getString(R.string.text_rex)));
            //昨日销毁
            num7.setText(MessageFormat.format("{0}{1} ", NumberUtils.big8(Double.parseDouble(bean.getWholeNetworkInfo().getYesterdayTotalDestroy())), getString(R.string.text_rex)));
            //总挖出
            totalMings.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getWholeCirculation().getTotalMings())), getString(R.string.text_rex)));
            //排单
            totalWaiting.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getWholeCirculation().getTotalWaiting())), getString(R.string.text_rex)));
            //质押
            totalPledge.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getWholeCirculation().getTotalPledge())), getString(R.string.text_rex)));
            //销毁
            totalDestroy.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getWholeCirculation().getTotalDestroy())), getString(R.string.text_rex)));

            //流动池RET
            rollingPoolRet.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getEachPoolBalance().getRollingPoolRET())), getString(R.string.text_rex)));
            //流动池RUSD
            rollingPoolRUSD.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getEachPoolBalance().getRollingPoolRUSD())), getString(R.string.text_xusd)));
            //销毁池
            destroyPoolRET.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getEachPoolBalance().getDestroyPoolRET())), getString(R.string.text_rex)));
            //竞技池
            sportsPoolRET.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getEachPoolBalance().getSportsPoolRET())), getString(R.string.text_rex)));
            //借贷池
            loanPoolRET.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getEachPoolBalance().getLoanPoolRUSD())), getString(R.string.text_xusd)));
            //个人复兴值
            pledgeAmount = bean.getTotalPledgeAward().getPledgeAmount();
            message1.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(pledgeAmount))));
            //个人排单值
            waitingPledgeAmount = bean.getTotalPledgeAward().getWaitingPledgeAmount();
            message2.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(waitingPledgeAmount))));
            //累计收益
            totalAward = bean.getTotalPledgeAward().getTotalAward();
            message3.setText(MessageFormat.format("{0}", NumberUtils.big8(Double.parseDouble(totalAward)), getString(R.string.text_rex)));
            //昨日收益
            yesterdayAward = bean.getTotalPledgeAward().getYesterdayAward();
            message4.setText(MessageFormat.format("{0}", NumberUtils.big8(Double.parseDouble(yesterdayAward)), getString(R.string.text_rex)));
            // 设置我的等级图标
            if (bean.getUserTeamInfo().getFissionLevel() != 0) {
                tv_my_level_empty.setVisibility(View.GONE);
                icon_my_level.setVisibility(View.VISIBLE);
                setMyLevelData(bean.getUserTeamInfo().getFissionLevel());
            }
            //设置社区等级图标
            if (bean.getUserTeamInfo().getCommunityLevel() != 0) {
                tv_community_level_empty.setVisibility(View.GONE);
                icon_community_level.setVisibility(View.VISIBLE);
                setCommunityData(bean.getUserTeamInfo().getCommunityLevel());
            }
            //直推人数
            tv_direct.setText(String.valueOf(bean.getUserTeamInfo().getDirectUserCount()));
            //团队有效用户
            tv_teamValid.setText(String.valueOf(bean.getUserTeamInfo().getAllEffectUser()));
            //团队复兴值
            if (bean.getUserTeamInfo().getTeamPledgeAmount() != null && !bean.getUserTeamInfo().getTeamPledgeAmount().isEmpty()) {
                fxCount.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(bean.getUserTeamInfo().getTeamPledgeAmount()))));
            }
            //排单复兴值
            if (bean.getUserTeamInfo().getTeamWaitingPledgeAmount() != null && !bean.getUserTeamInfo().getTeamWaitingPledgeAmount().isEmpty()) {
                tv_pd_count.setText(MessageFormat.format("{0}R", NumberUtils.big8(Double.parseDouble(bean.getUserTeamInfo().getTeamWaitingPledgeAmount()))));
            }
            myRoundProcess5.setProgress(bean.getEachPoolBalance().getRollingPoolRETRate() * 100);
            myRoundProcess4.setProgress(bean.getEachPoolBalance().getRollingPoolRUSDRate() * 100);
            myRoundProcess3.setProgress(bean.getEachPoolBalance().getDestroyPoolRETRate() * 100);
            myRoundProcess2.setProgress(bean.getEachPoolBalance().getSportsPoolRETRate() * 100);
            myRoundProcess1.setProgress(bean.getEachPoolBalance().getLoanPoolRUSDRate() * 100);

            totalPlacement.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                    LogUtil.error("addOnLayoutChangeListener:", "xxxxxx");
                    totalMingsPb.setProgress((int) (bean.getWholeCirculation().getMingsRate() * 100));
                    totalWaitingPb.setProgress((int) (bean.getWholeCirculation().getWaitingRate() * 100));
                    totalPledgePb.setProgress((int) (bean.getWholeCirculation().getPledgeRate() * 100));
                    totalDestroyPb.setProgress((int) (bean.getWholeCirculation().getDestroyRate() * 100));
                    totalPlacementPb.setProgress((int) (bean.getWholeCirculation().getPlacementRate() * 100));
                    calculator(totalMingsPb, totalMings, totalMingsLayout);
                    calculator(totalWaitingPb, totalWaiting, totalWaitingLayout);
                    calculator(totalPledgePb, totalPledge, totalPledgeLayout);
                    calculator(totalDestroyPb, totalDestroy, totalDestroyLayout);
                    calculator(totalPlacementPb, totalPlacement, totalPlacementLayout);
                }
            });
            //私募
            totalPlacement.setText(MessageFormat.format("{0}{1}", NumberUtils.big8(Double.parseDouble(bean.getWholeCirculation().getTotalPlacement())), getString(R.string.text_rex)));
            setTitlePrice();
        }
        mySmartRefreshLayout.finishRefresh();
    }


    private void setTitlePrice() {
        String stringPreference = PreferenceUtils.getString(AppConstants.CURRENCY_TYPE_KEY, "");
        if (stringPreference.equals(AppConstants.USD)) {
            ivPrice.setText(MessageFormat.format(getString(R.string.text_rex) + "实时价格：{0}{1}", NumberUtils.big8(Double.parseDouble(retPrice)), getResources().getString(R.string.text_usd)));
            return;
        }
        ivPrice.setText(MessageFormat.format(getString(R.string.text_rex) + "实时价格： {0}{1}", NumberUtils.big8(Double.parseDouble(retPriceCNY)), getResources().getString(R.string.string_cny)));
    }

    private void calculator(ProgressBar bar, TextView textView, RelativeLayout rootView) {
        double barWidth = bar.getProgress() / 100.00 * bar.getWidth();
        int textViewWidth = textView.getWidth() + 50;
        if (barWidth < textViewWidth) {
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = (int) barWidth;
            lp.addRule(RelativeLayout.CENTER_VERTICAL);
            textView.setLayoutParams(lp);
            textView.setTextColor(getResources().getColor(R.color.black));
        }
        LogUtil.error("xxxxxxbar:", barWidth + "");
        LogUtil.error("xxxxxxtextView:", textViewWidth + "");
    }


}